package com.idea.plugin.core.helper;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


/**
 * Freemarker工具
 *
 * @author yanzhao
 * @date 2021/12/6 23:15
 * @since 1.0.0
 */
public class FMUtils {

    public static final String basePackagePath = "/unittest";

    /**
     * classpath
     */
    private static Configuration classPathConfiguration;

    public static Configuration getClassPathConfiguration() throws IOException {
        if (classPathConfiguration != null) {
            return classPathConfiguration;
        }

        synchronized (FMUtils.class) {
            if (classPathConfiguration != null) {
                return classPathConfiguration;
            }

            classPathConfiguration = new Configuration(Configuration.VERSION_2_3_30);
            classPathConfiguration.setDefaultEncoding("utf-8");

            classPathConfiguration.setClassForTemplateLoading(FMUtils.class, basePackagePath);

            return classPathConfiguration;
        }
    }

    public static void writeFromClasspath(String path, File file, Object param) throws IOException, TemplateException {
        Configuration configuration = FMUtils.getClassPathConfiguration();
        write(path, file, param, configuration);
    }

    public static void write(String path, File file, Object param, Configuration configuration) throws IOException, TemplateException {
        Template template = configuration.getTemplate(path);
        Writer out = new FileWriter(file);
        template.process(param, out);
        out.flush();
        out.close();
    }
}
